package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Mr_Su
 * @version v1.0
 * @date 2022/6/25 12:27
 * @desciption 频道信息表 服务实现类
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {
    @Override
    public ResponseResult listByName(ChannelDto dto) {

        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 构建分页对象
        Page<WmChannel> pageInfo = new Page<>(dto.getPage(),dto.getSize());
        // 构建查询对象
        LambdaQueryWrapper<WmChannel> lqwWmChannel = new LambdaQueryWrapper<>();
        // 根据频道名称模糊查询
        lqwWmChannel.like(StringUtils.isNotBlank(dto.getName()),WmChannel::getName,dto.getName());
        // 调用方法
        this.page(pageInfo,lqwWmChannel);
        // 构建分页结果对象,并返回
        return new PageResponseResult<>(dto.getPage(),dto.getSize(),pageInfo.getTotal(),pageInfo.getRecords());
    }

    @Override
    public ResponseResult addWmChannel(WmChannel wmChannel) {
        // 如果参数为空 返回错误信息
        if (wmChannel == null || StringUtils.isBlank( wmChannel.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 根据名称判断这个频道是否已经存在
        LambdaQueryWrapper<WmChannel> lqwWmChannel = new LambdaQueryWrapper<>();
        lqwWmChannel.eq(WmChannel::getName,wmChannel.getName());
        WmChannel one = this.getOne(lqwWmChannel);
        if (one != null){
            // 如果频道已经存在,给出提示
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        // 频道不存在,保存
        wmChannel.setCreatedTime(new Date());
        this.save(wmChannel);

        return ResponseResult.okResult();
    }
}
